package org.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileDownloader {


    // 递归处理每个目录
    public static void processDirectory(String path, String localPath) throws Exception {
        // 获取当前目录下的文件列表
        List<FileInfo> files = getFilesInDirectory(path);
        for (FileInfo file : files) {
            if (file.isDirectory()) {
                // 如果是目录，递归处理子目录
                System.out.println("Entering directory: " + file.getFileName());
                processDirectory(path + "/" + file.getFileName(), localPath + "/" + file.getFileName());
            } else {
                // 如果是文件，拉取文件
                System.out.println("Pulling file: " + file.getFileName());
                pullFile(path + "/" + file.getFileName(), localPath + "/" + file.getFileName());
            }
        }
    }

    // 模拟执行 adb pull 命令
    private static void pullFile(String remotePath, String localPath) throws IOException {
        // 拼接 adb pull 命令
        String command = "adb pull " + remotePath + " \"" + localPath + "\"";
        System.out.println("Executing: " + command);
        // 执行命令
        Process process = Runtime.getRuntime().exec(command);
        try {
            process.waitFor(); // 等待命令执行完成
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 从远程目录获取文件列表
    private static List<FileInfo> getFilesInDirectory(String path) throws Exception {
        // 运行 adb shell ls -lh 命令获取目录下的文件
        String command = "adb shell ls -lh " + path;
        Process process = Runtime.getRuntime().exec(command);

        // 获取命令输出
        List<String> outputLines = new ArrayList<>();
        try (BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                outputLines.add(line);
            }
        }

        // 解析命令输出
        return LsOutputParser.parseLsOutput(outputLines);
    }

    static final String localPath = "C:/Users/yangyang/Desktop/data-sync";

    public static void main(String[] args) {
        try {
            // 从某个路径开始处理
            processDirectory("/storage/emulated/0/DCIM", localPath);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
